#include "MeshCache.h"
#include "include/isnwString.h"
#include "SceneManager.h"

namespace ISNW
{
namespace scene
{
	IAnimateMesh* MeshCache::getmesh(const c8* filename)
	{
		core::string fname = g_pSceneManager->getfs()->getfilenamefrompath(filename);

		for(u32 i = 0; i < meshes.size(); ++i)
		{
			if(meshes[i].filename.icompare(fname) == 0)
			{
				return meshes[i].mesh;
			}
		}

		return 0;
	}

	const IAnimateMesh* MeshCache::getmesh(const c8* filename) const
	{
		core::string fname = g_pSceneManager->getfs()->getfilenamefrompath(filename);

		for(u32 i = 0; i < meshes.size(); ++i)
		{
			if(meshes[i].filename.icompare(fname) == 0)
			{
				return meshes[i].mesh;
			}
		}

		return 0;
	}

	void MeshCache::addmesh(const c8* filename,IAnimateMesh* mesh)
	{
		if(!filename || !mesh) return;

		core::string fname = g_pSceneManager->getfs()->getfilenamefrompath(filename);

		mesh->grab();

		MeshEntry me;
		me.filename = fname;
		me.mesh = mesh;

		meshes.push_back(me);

		return;
	}

	bool MeshCache::removemesh(const u32 idx)
	{
		if(idx >= meshes.size()) return false;

		meshes[idx].mesh->drop();

		meshes.erase(idx);

		return true;
	}

	bool MeshCache::removemesh(const IAnimateMesh* mesh)
	{
		u32 i;
		for( i = 0; i < meshes.size(); ++i)
		{
			if(meshes[i].mesh == mesh)
			{
				break;
			}
		}

		if(i < meshes.size())
		{
			meshes[i].mesh->drop();
			meshes.erase(i);
			return true;
		}

		return false;
	}

	bool MeshCache::removemesh(const c8* filename)
	{
		core::string fname = g_pSceneManager->getfs()->getfilenamefrompath(filename);

		u32 i;
		for(i = 0; i < meshes.size(); ++i)
		{
			if(meshes[i].filename == fname) break;
		}

		if(i < meshes.size())
		{
			meshes[i].mesh->drop();
			meshes.erase(i);
			return true;
		}

		return false;
	}

} // end namespace scene
} // end namespace ISNW